package com.ruoyi.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.user.mapper.UserFriendMapper;
import com.ruoyi.user.model.constant.UserConstant;
import com.ruoyi.user.model.pojo.entity.User;
import com.ruoyi.user.model.pojo.entity.UserFriend;
import com.ruoyi.user.service.IUserFriendService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-08-06
 */
@Service
public class UserFriendServiceImpl extends ServiceImpl<UserFriendMapper, UserFriend> implements IUserFriendService {

    @Override
    public boolean addUsers(Long userId, List<User> records) {
        List<UserFriend> userFriends = new ArrayList<>();
        for (User record : records) {
            UserFriend one = lambdaQuery()
                    .eq(UserFriend::getUserId, userId)
                    .eq(UserFriend::getAimUserId, record.getId())
                    .one();
            if (CommonUtils.isNull(one)) {
                one = new UserFriend();
                one.setUserId(userId);
                one.setAimUserId(record.getId());
                userFriends.add(one);
            }
        }
        return saveBatch(userFriends);
    }

    @Override
    public Integer isFriend(Long userId, Long aimUserId) {
        Long count = lambdaQuery().eq(UserFriend::getUserId, userId).eq(UserFriend::getAimUserId, aimUserId).count();
        if (count > 0) return 1;
        return 0;
    }

    @Override
    public Integer setFriend(Long userId, Long aimUserId) {
        Long count = lambdaQuery()
                .eq(UserFriend::getUserId, userId)
                .eq(UserFriend::getAimUserId, aimUserId)
                .count();
        if (count == 0) {
            UserFriend userFriend = new UserFriend();
            userFriend.setAimUserId(aimUserId);
            userFriend.setUserId(userId);
            userFriend.setIsUndock(UserConstant.IsUndock.XJ);
            save(userFriend);
            return 1;
        } else {
            remove(new QueryWrapper<UserFriend>().lambda().eq(UserFriend::getAimUserId, aimUserId).eq(UserFriend::getUserId, userId));
            return 0;
        }
    }

    @Override
    public Long friendCount(Long aimUserId) {
        Long count = lambdaQuery().eq(UserFriend::getUserId, aimUserId).eq(UserFriend::getIsUndock, UserConstant.IsUndock.XJ).count();
        if (CommonUtils.isNull(count)) return 0L;
        return count;
    }
}
